/**
 * 
 */
package com.dfhc.tag;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;

import org.apache.commons.collections.MapUtils;
import org.quickbundle.project.RmGlobalReference;
import org.quickbundle.project.RmProjectHelper;
import org.quickbundle.project.common.vo.RmCommonVo;

import com.dfhc.ISystemConstant;
import com.dfhc.PjException;
import com.dfhc.util.CryptoHelper;
import com.dfhc.util.StringHelper;
import com.dfhc.util.TemplateHelper;

import freemarker.template.TemplateException;

/**
 * @author 龙色波
 * 处理tag
 */
public class ParseDynamicTag {
	/**
	 * 属性map
	 */
	private Map attributesMap = null;
	/**
	 * 中间文本
	 */
	private String body;
	/**
	 * 标签类型
	 */
	private String tagType;
	/**
	 * 页面的请求对象
	 */
	private ServletRequest  servletRequest;
	public Map getAttributesMap() {
		return attributesMap;
	}
	public void setAttributesMap(Map attributesMap) {
		this.attributesMap = attributesMap;
	}
	public String getBody() {
		return body;
	}
	public void setBody(String body) {
		this.body = body;
	}
	public String getTagType() {
		return tagType;
	}
	public void setTagType(String tagType) {
		this.tagType = tagType;
	}
	/**
	 * 解析标签
	 */
	public String parse(){
		String templateKey;
    	if(!attributesMap.containsKey(ISystemConstant.TAG_TEMPLATE_ID)){
    		if(tagType.equals(TagItem.TAG_TYPE_CHECKBOX)){
    			templateKey = ISystemConstant.DICTIONARY_TAG_CHECKBOX_TEMPLATE;
    		}else if(tagType.equals(TagItem.TAG_TYPE_INPUT)){
    			templateKey = ISystemConstant.DICTIONARY_TAG_INPUT_TEMPLATE;
    		}else if(tagType.equals(TagItem.TAG_TYPE_RADIO)){
    			templateKey = ISystemConstant.DICTIONARY_TAG_RADIO_TEMPLATE;
    		}else if(tagType.equals(TagItem.TAG_TYPE_SELECT)){
    			templateKey = ISystemConstant.DICTIONARY_TAG_SELECT_TEMPLATE;
    		}else if(tagType.equals(TagItem.TAG_TYPE_TABLE)){
    			templateKey = ISystemConstant.DICTIONARY_TAG_TABLE_BEGIN_TEMPLATE;
    		}else if(tagType.equals(TagItem.TAG_TYPE_TD)){
    			templateKey = ISystemConstant.DICTIONARY_TAG_TD_TEMPLATE;
    		}else if(tagType.equals(TagItem.TAG_TYPE_TH)){
    			templateKey = ISystemConstant.DICTIONARY_TAG_TH_TEMPLATE;
    		}else if(tagType.equals(TagItem.TAG_TYPE_TITLE)){
    			templateKey = ISystemConstant.DICTIONARY_TAG_TITLE_DEFAULT_TEMPLATE;
    		}else if(tagType.equals(TagItem.TAG_TYPE_TR)){
    			templateKey = ISystemConstant.DICTIONARY_TAG_TR_BEGIN_TEMPLATE;
    		}else{
    			throw new PjException("缺少模板id");
    		}
		}else{
			templateKey = (String)attributesMap.get(ISystemConstant.TAG_TEMPLATE_ID);
		}
        
		String buttonHtml = RmGlobalReference.get(ISystemConstant.DICTIONARY_TAG_TEMPLATE, templateKey);
		if(StringHelper.isEmpty(buttonHtml)){
			throw new PjException("尚未配置模板(模板Id:"+templateKey+"尚未配置模板，请在编码表增加!");
		}
		Map<String,Object> rootMap = new HashMap<String,Object>();
		//如果包含双击事件或单击事件,则对单引号里头url加密
		if(TagItem.TAG_TYPE_BUTTON.equals(tagType)||
		   TagItem.TAG_TYPE_LABEL.equals(tagType)||
		   TagItem.TAG_TYPE_TR.equals(tagType)
				
				){
			try {
				CryptoHelper.encryptEventUrl(servletRequest,attributesMap);
			} catch (Exception e) {
				e.printStackTrace();
				throw new PjException(e);
			}		
		}
		//如果是下拉框:select 则需特殊处理
		if(!TagItem.TAG_TYPE_SELECT.equals(tagType)){
			//删除模块id属性,防止生成到界面
			attributesMap.remove(ISystemConstant.TAG_TEMPLATE_ID);
			rootMap.put(ISystemConstant.ATTRIBUTES_MAP_KEY, attributesMap);
			if(!StringHelper.isEmpty(body)){
				rootMap.put(ISystemConstant.TABLEBODY_MAP_KEY, body);
			}
	        try {
				return TemplateHelper.createContentByString(rootMap, buttonHtml);
	        } catch (Exception e) {
				e.printStackTrace();
				throw new PjException(e);
			}
		}else{
			try {
				return buildSelectHTML();
	        } catch (Exception e) {
				e.printStackTrace();
				throw new PjException(e);
			}
		}
	}
	public ServletRequest getServletRequest() {
		return servletRequest;
	}
	public void setServletRequest(ServletRequest servletRequest) {
		this.servletRequest = servletRequest;
	}
	public  Map<String, Object>  getSqlOption(Map attributesMap) throws IOException, TemplateException{    	
	        //sqlOption
	        String type = MapUtils.getString(attributesMap, ISystemConstant.DICTIONARY_FRAMEWORK_DEFAULT_SQLOPTION);// 区分编码表  还是sql
	        if(StringHelper.isEmpty(type)){
	        	throw new IOException("缺少sqlOption属性!");
	        }        
	        switch (type.toUpperCase()) {
		        case "SQL":
	//	        	columnId
		        	String columnId  = MapUtils.getString(attributesMap, ISystemConstant.DICTIONARY_FRAMEWORK_DEFAULT_COLUMNID);
		        	//columnName
		        	String columnName  = MapUtils.getString(attributesMap, ISystemConstant.DICTIONARY_FRAMEWORK_DEFAULT_COLUMNNAME);
		        	//sql
		        	String sql  = MapUtils.getString(attributesMap, ISystemConstant.DICTIONARY_FRAMEWORK_SELECT_SQL);
	//	        	conditions
	//	        	String conditions = MapUtils.getString(attributesMap, ISystemConstant.DICTIONARY_FRAMEWORK_DEFAULT_CONDITIONS);
		        	
		        	//String sql="select "+columnId+"  as id, "+columnName+" as  name     from "+tableName+" "+conditions;
		        	if(StringHelper.isEmpty(columnId)){
		        		throw new IOException("缺少columnId属性!");
		        	}
		        	if(StringHelper.isEmpty(columnName)){
		        		throw new IOException("缺少columnName属性!");
		        	}
		        	if(StringHelper.isEmpty(sql)){
		        		throw new IOException("缺少sql属性!");
		        	}
		        	
					List<RmCommonVo> lvos = RmProjectHelper.getCommonServiceInstance().doQuery(sql);
					if(!lvos.isEmpty()){
						Map<String, Object>  map=null;
						map=new HashMap<String, Object>();
						for (int i = 0; i < lvos.size(); i++) {
							map.put(lvos.get(i).getString(columnId),lvos.get(i).get(columnName));						
						}
						return map;
					}
		        	
		        	break;
		        case "CODE":
		        	Map<String, Object>   map =RmGlobalReference.get(MapUtils.getString(attributesMap, ISystemConstant.DICTIONARY_FRAMEWORK_DEFAULT_CODE));
		        	return map;
		        default:
		            break;
	        }
	        
	        
	    	return  new HashMap<String,Object>();
	    }
	private String buildSelectHTML() throws IOException, TemplateException{
	    //option
	    Map<String,Object> optionMap=getSqlOption(attributesMap);
	    
	    String defaultValue = MapUtils.getString(attributesMap, ISystemConstant.DICTIONARY_FRAMEWORK_DEFAULT_DEFAULTVALUE);
	    String templateKey ;
		if(!attributesMap.containsKey(ISystemConstant.TAG_TEMPLATE_ID)){
			templateKey= ISystemConstant.DICTIONARY_TAG_SELECT_TEMPLATE;
		}else{
			templateKey = (String)attributesMap.get(ISystemConstant.TAG_TEMPLATE_ID);
		}
	    String selectHtml =RmGlobalReference.get(ISystemConstant.DICTIONARY_TAG_TEMPLATE, templateKey);
	    if(StringHelper.isEmpty(selectHtml)){
	    	throw new IOException("下拉框尚未配置模板(模板Id:"+templateKey+")，请在编码表增加!");
	    }
	    Map<String,Object> rootMap = new HashMap<String,Object>();
		//属性map
	    rootMap.put(ISystemConstant.ATTRIBUTES_MAP_KEY, attributesMap);
	    //下拉项map
		rootMap.put(ISystemConstant.OPTIONS_MAP_KEY,optionMap);
		//默认选中项
		if(!StringHelper.isEmpty(defaultValue)){
			rootMap.put(ISystemConstant.SELECT_DEFAULT_VALUE, defaultValue);
		}
		//是否出现”--请选择--"
		String pleaseSelect = MapUtils.getString(attributesMap, ISystemConstant.PLEASE_SELECT);
		if(!StringHelper.isEmpty(pleaseSelect)){
			rootMap.put(ISystemConstant.PLEASE_SELECT, pleaseSelect);
		}
	    return TemplateHelper.createContentByString(rootMap, selectHtml);
	    
	}
}
